package com.uenpay.im.ui.old.activity.stickers;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.weight.jpg2gif.QyxAnimatedGifEncoder;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.SendFileResult;
import com.uenpay.im.invokeitems.chat.OnAttachedListener;
import com.uenpay.im.invokeitems.chat.UploadMessageAttachment;
import com.uenpay.im.weight.ZProgressHUD;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

/**
 * @author SL
 * @version 1.0
 * @copyRight http://www.qiyunxin.com
 * @date 2016-6-1 下午1:58:07
 * @function 创建表情
 */
public class CreateStickerActivity extends BaseActivity {

    private MaskImageView custom_iv;
    private String file_path;
    private FileUtils fileUtils = new FileUtils(IMApplication.appName);
    private ZProgressHUD zProgressHUD = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_create_sticker_layout;
    }

    @Override
    public void initView(View view) {
        file_path = getIntent().getStringExtra("path");
        initView();
        initListener();
    }

    protected void initView() {
        zProgressHUD = new ZProgressHUD(this);
        ((TextView) findViewById(R.id.title_textview)).setText("");
        ((TextView) findViewById(R.id.title_right_tv))
                .setText(R.string.use_face);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        custom_iv = (MaskImageView) findViewById(R.id.custom_iv);
        custom_iv.SetUrl(file_path);
    }

    protected void initListener() {
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO 添加表情
                        if (!TextUtils.isEmpty(file_path)) {
                            zProgressHUD.show();
                            findViewById(R.id.title_right_layout).setEnabled(
                                    false);
                            uploadFace();
                        }
                    }
                });
    }

    private void uploadFace() {
        OnAttachedListener mOnAttachedListener = new OnAttachedListener() {

            @Override
            public void onAttached(SendFileResult sendResult, boolean isFailed) {
                if (!isFailed && !TextUtils.isEmpty(sendResult.getFileHash())
                        && !TextUtils.isEmpty(sendResult.getFileId())) {
                    addCustomFace(sendResult.getFileId(),
                            sendResult.getFileHash());
                } else {
                    zProgressHUD.dismiss();
                    findViewById(R.id.title_right_layout).setEnabled(true);
                }
            }
        };

        UploadMessageAttachment(file_path, mOnAttachedListener);
    }

    /**
     * 添加表情
     *
     * @param fileId
     * @param fileHash
     */
    private void addCustomFace(final String fileId, final String fileHash) {

        final JSONObject customFaceJson = new JSONObject();
        try {
            customFaceJson.put("fileid", fileId);
            customFaceJson.put("filehash", fileHash);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        StickersHandle.addSticker(customFaceJson.toString(),
                new StickersHandle.IAddStickerListener() {

                    @Override
                    public void onAddStrickerResult(int status, String msg,
                                                    String favoriteid) {
                        zProgressHUD.dismiss();
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            try {
                                customFaceJson.put("favoriteid", favoriteid);
                                customFaceJson.put("customefaceurl",
                                        APIConfiguration.getFileDownloadPath(
                                                fileId, fileHash));
                                saveCustomFaceToLocal(customFaceJson);
                                setResult(RESULT_OK);
                                finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else if (!TextUtils.isEmpty(msg)) {
                            findViewById(R.id.title_right_layout).setEnabled(
                                    true);
                        }
                    }
                });
    }

    /**
     * 上传表情附件
     *
     * @param file_path
     * @param onAttachedListener
     */
    private void UploadMessageAttachment(String file_path,
                                         OnAttachedListener onAttachedListener) {
        if (TextUtils.isEmpty(file_path)) {
            return;
        }

        String[] arrs = null;
        try {
            arrs = file_path.split("\\.");// 后缀名
            if (arrs.length < 2) {
                arrs = file_path.split("\\/");// 后缀名
            }
        } catch (Exception e) {
            arrs[0] = "log";
            arrs[1] = "error";
        }

        String end = arrs[arrs.length - 1];

        if (!end.equals("gif") && !end.equals("GIF")) {
            Bitmap compressBitmap = ImageUtil.CompressImageSameRadioScale(
                    file_path, 80, 300, 300);
            String big_pic_filename = fileUtils.getAlbumDir() + "/"
                    + Utils.md5(file_path) + ".jpg";
            byte[] bytes = fileUtils.compressPicAndSaveReturnBytes(
                    compressBitmap, big_pic_filename, CompressFormat.JPEG, 80);

            String filepath = Environment.getExternalStorageDirectory()
                    + "/temp.gif";
            String[] strs = new String[1];
            strs[0] = big_pic_filename;
            /** png、jpg转gif **/
            jpg2gif(strs, filepath);
            File gifFile = new File(filepath);
            try {
                bytes = Utils.getBytesFromFile(gifFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // TODO 判断是否存在该表情
            if (!isExiste(gifFile)) {
                new UploadMessageAttachment(bytes, "gif",
                        IMApplication.getAppContext(), onAttachedListener);
            } else {
                IMApplication.showToast(R.string.added_friend);
                finish();
            }

        } else {
            byte[] file_bytes = null;
            File file = new File(file_path);
            try {
                file_bytes = Utils.getBytesFromFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // TODO 判断是否存在该表情
            if (!isExiste(file)) {
                new UploadMessageAttachment(file_bytes, "gif",
                        IMApplication.getAppContext(), onAttachedListener);
            } else {
                IMApplication.showToast(R.string.added_friend);
                finish();
            }
        }
    }

    private void saveCustomFaceToLocal(JSONObject customFaceJson) {
        if (customFaceJson != null) {
            try {

                String jsonStr = IMApplication.config
                        .getCustomFaceJson(IMApplication.getCustId());
                JSONArray jsonArray = null;
                if (!TextUtils.isEmpty(jsonStr)) {
                    jsonArray = new JSONArray(jsonStr);
                } else {
                    jsonArray = new JSONArray();
                }
                if (jsonArray != null) {
                    jsonArray.put(customFaceJson);
                    IMApplication.config.setCustomFaceJson(
                            IMApplication.getCustId(), jsonArray.toString());
                    // 通知会话页面更新数据
                    Intent intent = new Intent(
                            BroadcastAction.ACTION_REFRESH_STICKER);
                    IMApplication.getAppContext().sendBroadcast(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void jpg2gif(String pic[], String newPic) {
        try {
            QyxAnimatedGifEncoder e = new QyxAnimatedGifEncoder();
            e.setRepeat(1);
            e.start(newPic);
            for (int i = 0; i < pic.length; i++) {
                e.setDelay(200); // 设置播放的延迟时间
                Bitmap src = BitmapFactory.decodeFile(pic[i]);
                e.addFrame(src); // 添加到帧中
            }
            e.finish();// 刷新任何未决的数据，并关闭输出文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isExiste(File file) {
        String customJson = IMApplication.config
                .getCustomFaceJson(IMApplication.getCustId());
        if (TextUtils.isEmpty(customJson)) {
            return false;
        } else {
            boolean isExiste = false;
            try {
                JSONArray jsonArray = new JSONArray(customJson);
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0, size = jsonArray.length(); i < size; i++) {
                        JSONObject jsonObject = jsonArray.optJSONObject(i);
                        String fileHash = jsonObject.optString("filehash");
                        String fileId = jsonObject.optString("fileid");
                        String temp = HttpStreamCache.getInstance()
                                .GetFilePath(
                                        APIConfiguration.getFileDownloadPath(
                                                fileId, fileHash));
                        if (!TextUtils.isEmpty(temp)) {
                            File tempFile = new File(temp);
                            if (fileUtils.compareFileIden(file, tempFile)) {
                                isExiste = true;
                                break;
                            }
                        }
                    }
                    return isExiste;
                }
                return isExiste;
            } catch (JSONException e) {
                e.printStackTrace();
                return isExiste;
            }
        }
    }

}
